package com.domain.service.impl;

import com.domain.common.AppLogger;
import com.domain.common.Comments;
import com.domain.common.Const;
import com.domain.common.Result;
import com.domain.dao.*;
import com.domain.pojo.*;
import com.domain.service.IndexService;
import com.domain.service.PushMessageService;
import com.domain.service.UsersRelationshipService;
import com.domain.utils.DateUtils;
import com.domain.utils.NotNullUtils;
import com.domain.utils.RelativeDateFormat;
import com.domain.utils.UUIDUtils;
import com.domain.utils.jiguang.Jdpush;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
@Transactional(rollbackFor = Exception.class)
public class IndexServiceImpl implements IndexService {
    /**
     * 日志
     */
    private static Logger logger = AppLogger.getLogger(IndexServiceImpl.class.getSimpleName(), Level.INFO.toString(), true);

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private ReportTypeMapper reportTypeMapper;
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private FollowMapper followMapper;
    @Autowired
    private UsersHelpMapper usersHelpMapper;
    @Autowired
    private PublishMapper publishMapper;

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private PublishAcceptanceMapper publishAcceptanceMapper;

    @Autowired
    private ContactsMapper contactsMapper;

    @Autowired

    private PushMessageService pushMessageService;


    @Autowired
    private UsersFillterUsersMapper usersFillterUsersMapper;

    @Autowired
    private PublishTypeMapper publishTypeMapper;

    @Autowired
    private UsersCityHistoryMapper usersCityHistoryMapper;

    @Autowired
    private UsersFillterPublishUsersMapper usersFillterPublishUsersMapper;

    @Autowired
    private UsersRelationshipService usersRelationshipService;

    @Autowired
    private UsersSmsRecordMapper usersSmsRecordMapper;

    @Autowired
    private UsersRelationshipMapper usersRelationshipMapper;


    /**
     * 获取评论列表
     *
     * @param publishId
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result getCommentPublishList(String publishId, String pageNum, String pageSize) {
        PageHelper.startPage(new Integer(pageNum), new Integer(pageSize));
        List<Map<String, Object>> comments = commentMapper.selectBypublishIdDetail(publishId);
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Map<String, Object> map : comments) {
            map.put("content", map.get("content").toString());
            map.put("times", RelativeDateFormat.format(DateUtils.strToDate(map.get("times").toString(), "yyyy-MM-dd HH:mm:ss")));
            mapList.add(map);
        }
        PageInfo pageInfo = new PageInfo(mapList);
        return Result.success("操作成功", pageInfo.getList());
    }

    /**
     * 发布评论
     *
     * @param userId    评论人id
     * @param content   评论内容
     * @param publishId 发布id
     * @return
     */
    @Override
    public Result addComment(String userId, String content, String publishId) {
        Comment comment = new Comment();
        String commentuuid = UUIDUtils.getRandomUUID();
        comment.setId(commentuuid);
        comment.setCommentTime(new Date());
        comment.setContent(content);
        comment.setCreatTime(new Date());
        comment.setPublishId(publishId);
        comment.setUserId(userId);
        int result = commentMapper.insertSelective(comment);
        if (result > 0) {
            //获取发布人id
            Publish publish = publishMapper.selectByPrimaryKey(publishId);
            //评论成功推送消息至发布人  文案：你的帮忙信息收到一条新的评论
            String pushuuid = UUIDUtils.getRandomUUID();
            Jdpush.sendToAliasList(publish.getUserId(), "你的帮忙信息收到一条新的评论", "pushId", pushuuid, "pushType", Const.comment, "bigTypeKey", Const.PUBLISH_MESSAGE, "评论通知");
            //添加推送记录
            pushMessageService.addPublishiMessage(publish.getUserId(), userId, content, "评论通知", publishId, Const.comment, pushuuid, "");
        }
        return Result.success();
    }

    /**
     * 获取举报类型
     *
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result getReportType() {
        List<ReportType> reportTypes = reportTypeMapper.selectList();
        return Result.success("操作成功", reportTypes);
    }

    /**
     * 举报
     *
     * @param userId       举报人id
     * @param reportTypeId 举报类型id
     * @param content      举报内容
     * @param images       举报图片
     * @param publishId    发布帮忙id
     * @return
     */
    @Override
    public Result addReport(String userId, String reportTypeId, String content, String images, String publishId) {
        Report report = new Report();
        report.setId(UUIDUtils.getRandomUUID());
        report.setPublishId(publishId);
        report.setReportTime(new Date());
        report.setCreatTime(new Date());
        report.setReportContent(content);
        report.setReportImage(images);
        report.setUserId(userId);
        report.setReportType(reportTypeId);
        int result = reportMapper.insertSelective(report);
        if (result > 0) {
            //获取推送人id
            Publish publish = publishMapper.selectByPrimaryKey(publishId);
            String pushuuid = UUIDUtils.getRandomUUID();
            //推送举报  文案  您发布的帮忙信息有违规内容
            Jdpush.sendToAliasList(publish.getUserId(), "您发布的帮忙信息有违规内容", "pushId", pushuuid, "pushType", Const.report_feedback, "bigTypeKey", Const.SYSTEM_MESSAGE, "违规提醒");
            //添加推送记录
            pushMessageService.addSystemMessage(publish.getUserId(), userId, "您发布的帮忙信息有违规内容", "违规提醒", publishId, Const.report_feedback, pushuuid, "");
        }
        return Result.success();
    }

    /**
     * 添加关注
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Result addFollow(String userId, String publishId, String helpUsersId) {
        Follow f = new Follow();
        f.setId(UUIDUtils.getRandomUUID());
        f.setFollowTime(new Date());
        f.setPublishId(publishId);
        f.setUserId(userId);
        f.setSpareOne(helpUsersId);
        followMapper.insertSelective(f);
        return Result.success();
    }

    /**
     * 获取我的关注列表
     *
     * @param userId
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result getUsersFollowList(String userId, String pageNum, String pageSize) {
        PageHelper.startPage(new Integer(pageNum), new Integer(pageSize));
        List<Map<String, Object>> list = new ArrayList<>();
        List<Follow> follows = followMapper.selectByUserIdsa(userId);
        for (Follow f : follows) {
            //获取发布信息
            Publish publish = publishMapper.selectByPrimaryKey(f.getPublishId());
            //获取发布用户信息
            Users users = usersMapper.selectByPrimaryKey(publish.getUserId());
            //获取发布类型
            Map<String, Object> maps = new HashMap<>();
            maps.put("followId", f.getId());
            if (NotNullUtils.isNotNullObject(users)) {
                maps.put("userName", users.getName());
                maps.put("userHead", users.getHeadImage());
            }
            if (NotNullUtils.isNotNullObject(publish)) {
                maps.put("publishRedPacakge", publish.getSpareTwo());
                maps.put("publishItisPaid", publish.getItIsPaid());
                maps.put("publishHelpSize", publish.getForwardCount());
                maps.put("publishTitle", publish.getTitle());
                maps.put("publishType", publish.getType());
                maps.put("publishId", publish.getId());
                maps.put("helpUsersId", f.getSpareOne());
                //获取评论次数
                List<Comment> comments = commentMapper.selectBypublishId(publish.getId());
                maps.put("publishCommentsSize", comments.size());
            }
            maps.put("publishTypeId", publish.getSpareOne());
            list.add(maps);
        }
        PageInfo pageInfo = new PageInfo(list);
        return Result.success("操作成功", pageInfo.getList());
    }


    /**
     * 帮转
     *
     * @param helpId    帮转人id
     * @param publishId 发布问题id
     * @param userId    发布人id
     * @return
     */
    @Override
    public Result helpPublish(String helpId, String publishId, String userId, String helpType) {
        logger.info("helpId++++++" + helpId);
        logger.info("publishId++++++" + publishId);
        logger.info("userId++++++" + userId);
        logger.info("helpId++++++" + helpId);
        logger.info("helpType++++++" + helpType);
        //判断该条发布转发人是否转发
        UsersHelp u = new UsersHelp();
        u.setPublishId(publishId);
        u.setHelpId(helpId);
        u.setHelpType(new Integer(helpType));
        UsersHelp up = usersHelpMapper.selects(u);
        if (!NotNullUtils.isNotNullObject(up)) {
            //分享到朋友或者分享到通讯录添加朋友圈
            if ("3".equals(helpType) || "4".equals(helpType) || "2".equals(helpType)) {
                UsersHelp us = new UsersHelp();
                us.setPublishId(publishId);
                us.setHelpId(helpId);
                us.setHelpType(1);
                UsersHelp ups = usersHelpMapper.selects(us);
                if (!NotNullUtils.isNotNullObject(ups)) {
                    UsersHelp help = new UsersHelp();
                    help.setId(UUIDUtils.getRandomUUID());
                    help.setCreatTime(new Date());
                    help.setHelpId(helpId);
                    help.setHelpTime(new Date());
                    help.setPublishId(publishId);
                    help.setUserId(userId);
                    help.setHelpType(1);
                    publishMapper.updateForwardCount(publishId);
                    usersHelpMapper.insertSelective(help);
                }
            }
            UsersHelp help = new UsersHelp();
            help.setId(UUIDUtils.getRandomUUID());
            help.setCreatTime(new Date());
            help.setHelpId(helpId);
            help.setHelpTime(new Date());
            help.setPublishId(publishId);
            help.setUserId(userId);
            help.setHelpType(new Integer(helpType));
            if ("1".equals(helpType)) {
                publishMapper.updateForwardCount(publishId);
            }
            int result = usersHelpMapper.insertSelective(help);
            if (result > 0) {
                //帮转成功以后推送发布人通知（不做推送  增加消息记录）文案：xxx 帮转了您发布的帮忙请求
                Users user = usersMapper.selectByPrimaryKey(helpId);
                if (!userId.equals(helpId)) {
                    pushMessageService.addPublishiMessage(userId, helpId, "" + user.getName() + "帮转了您发布的帮忙请求", "帮转通知", publishId, Const.help, UUIDUtils.getRandomUUID(), "" + user.getName() + "");
                }
                //转发第一条通讯录好友发送短信
                List<UsersHelp> usersHelps = usersHelpMapper.selectByUesd(helpId);
                if (usersHelps.size() == 1) {
                    List<Contacts> list = contactsMapper.selectByContUser(helpId);
                    for (Contacts c : list) {
                      /*  SmsVariableResponse response = SmsChuangLan.sendMessage(c.getSpareOne(), user.getName(), "1");
                        //短信发送成功添加发送记录
                        if (!NotNullUtils.isNotNullObject(response.getSuccessNum())) {
                            UsersSmsRecord sm = new UsersSmsRecord();
                            sm.setId(UUIDUtils.getRandomUUID());
                            sm.setCreatTime(new Date());
                            sm.setSendUsersId(helpId);
                            sm.setSendUsersId("");
                            sm.setUsersPhone(user.getPhone());
                            sm.setSendUsersPhone(c.getSpareOne());
                            usersSmsRecordMapper.insertSelective(sm);
                        }*/
                    }
                }
            }
        }
        //增加帮转记录
        return Result.success();
    }


    /**
     * 发布受理
     *
     * @param helpId            帮转人id
     * @param acceptanceId      受理人id
     * @param publishId         发布问题id
     * @param userId            发布人id
     * @param acceptanceMessage 受理留言
     * @return
     */
    @Override
    public Result publishAcceptance(String acceptanceId, String publishId, String userId, String acceptanceMessage, String helpId) {
        PublishAcceptance ps = publishAcceptanceMapper.selectByAcceptanIdAndPublishId(acceptanceId, publishId);
        if (NotNullUtils.isNotNullObject(ps)) {
            return Result.publicResult(403, "该发布已经受理");
        }
        /*添加受理记录*/
        PublishAcceptance p = new PublishAcceptance();
        String uuid = UUIDUtils.getRandomUUID();
        p.setId(uuid);
        p.setAcceptanceId(acceptanceId);
        p.setAcceptanceMessage(acceptanceMessage);
        p.setAcceptanceTime(new Date());
        p.setCreatTime(new Date());
        p.setPublishId(publishId);
        p.setUserId(userId);
        p.setSpareOne(Comments.ADOPT_NO);
        p.setSpareTwo(helpId);
        int result = publishAcceptanceMapper.insertSelective(p);
        if (result > 0) {
            //帮忙受理通知 xxx 接受了您得帮忙，赶快发起讨论组
            Users user = usersMapper.selectByPrimaryKey(acceptanceId);
            String pushId = UUIDUtils.getRandomUUID();
            Jdpush.sendToAliasList(userId, "" + user.getName() + "接受了您得帮忙，赶快发起讨论组", "pushId", pushId, "pushType", Const.notice_of_action, "bigTypeKey", Const.PUBLISH_MESSAGE, "受理通知");
            //如果推送成功添加推送记录
            //受理通知  spare_one 添加的是受理记录id
            pushMessageService.addPublishiMessage(userId, acceptanceId, "" + user.getName() + "接受了您得帮忙，赶快发起讨论组", "受理通知", uuid, Const.notice_of_action, pushId, "" + user.getName() + "");
        }
        return Result.success();
    }

    /**
     * 获取首页好友信息
     *
     * @param usersId
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public List<Map<String, Object>> getIndexUsersInfo(String usersId, String pageNum, String pageSize) {
        //获取我的app好友列表
        List<Contacts> contactsList = contactsMapper.selectByUsersIdAndType(usersId);
        PageHelper.startPage(new Integer(pageNum), new Integer(pageSize));
        List<Map<String, Object>> objectList = new ArrayList<>();
        for (Contacts c : contactsList) {
            //好友的好友
            List<Contacts> usersFriendsList = contactsMapper.selectByUsersIdAndType(c.getSpareTwo());
            //好友的好友去重直接好友
            if (!usersFriendsList.contains(contactsList)) {
                for (Contacts cs : usersFriendsList
                ) {
                    //获取好友的好友的发布
                    List<Publish> publishes = publishMapper.selectByUsersIdsAndpublishType(cs.getSpareTwo());
                    for (Publish p : publishes
                    ) {
                        logger.info("好友的好友发布标记");
                        if (!p.getUserId().equals(usersId)) {
                            if (!c.getSpareTwo().equals(p.getUserId())) {
                                Publish publish = publishMapper.selectByPrimaryKey(p.getId());
                                //好友信息
                                Users user = usersMapper.selectByPrimaryKey(c.getSpareTwo());
                                //获取发布者信息
                                Users users = usersMapper.selectByPrimaryKey(publish.getUserId());
                                Map<String, Object> objectMap = new HashMap<>();
                                objectMap.put("userId", users.getId());
                                objectMap.put("gender", users.getGender());
                                objectMap.put("userHead", users.getHeadImage());
                                objectMap.put("userName", users.getName());
                                objectMap.put("pCity", publish.getCityName());
                                objectMap.put("pTime", RelativeDateFormat.format(publish.getCreatTime()));
                                objectMap.put("pTypeId", publish.getSpareOne());
                                objectMap.put("pTitle", publish.getTitle());
                                objectMap.put("pContent", publish.getContent());
                                objectMap.put("pRedPacakge", publish.getSpareTwo());
                                //是否受理
                                if (NotNullUtils.isNotNullObject(publishAcceptanceMapper.selectByAcceptanIdAndPublishId(usersId, publish.getId()))) {
                                    objectMap.put("itisAppent", "YES");
                                } else {
                                    objectMap.put("itisAppent", "NO");
                                }
                                objectMap.put("pitisPaid", publish.getItIsPaid());

                                objectMap.put("time", DateUtils.dateToStr(publish.getCreatTime(), "yyyy-MM-dd HH:mm:ss"));

                                if (getFriends(usersId, users.getId())) {
                                    objectMap.put("connections", "我的好友");
                                } else {
                                    objectMap.put("connections", user.getName());
                                }
                                objectMap.put("connectionUserId", user.getId());
                                List<Comment> comments = commentMapper.selectBypublishId(publish.getId());
                                objectMap.put("commentSize", comments.size());
                                objectMap.put("pFowordCount", publish.getForwardCount());
                                List<Follow> followList = followMapper.selectByUserAndPublish(usersId, publish.getId());
                                if (followList.size() > 0) {
                                    objectMap.put("itisFollow", 1);
                                } else {
                                    objectMap.put("itisFollow", 2);
                                }
                                objectMap.put("publishId", publish.getId());
                                objectMap.put("helpUsersId", "");
                                objectList.add(objectMap);
                            }
                        }

                    }
                    //获取好友的好友的帮转
                  /*  List<Map<String, Object>> usersHelps = usersHelpMapper.selectIndexByUsersId(cs.getSpareTwo());
                    for (Map<String, Object> us : usersHelps
                    ) {
                        if (!us.get("usersId").equals(usersId)) {
                            if (!usersId.equals(us.get("helpId"))) {
                                Map<String, Object> objectMap = new HashMap<>();
                                Publish publishs = publishMapper.selectByPrimaryKey(us.get("publishId").toString());
                                //发布人
                                Users users = usersMapper.selectByPrimaryKey(us.get("usersId").toString());
                                //帮转人
                                Users user = usersMapper.selectByPrimaryKey(us.get("helpId").toString());
                                objectMap.put("userId", users.getId());
                                objectMap.put("userHead", users.getHeadImage());
                                objectMap.put("gender", users.getGender());
                                objectMap.put("userName", users.getName());
                                objectMap.put("pCity", publishs.getCityName());
                                objectMap.put("pTime", RelativeDateFormat.format(publishs.getCreatTime()));
                                objectMap.put("pTypeId", publishs.getSpareOne());
                                objectMap.put("pTitle", publishs.getTitle());
                                objectMap.put("pContent", publishs.getContent());
                                objectMap.put("pRedPacakge", publishs.getSpareTwo());
                                objectMap.put("pitisPaid", publishs.getItIsPaid());
                                objectMap.put("time", us.get("helpTime"));
                                objectMap.put("connections", users.getName());
                                objectMap.put("connectionUserId", c.getSpareTwo());
                                //是否受理
                                if (NotNullUtils.isNotNullObject(publishAcceptanceMapper.selectByAcceptanIdAndPublishId(usersId, publishs.getId()))) {
                                    objectMap.put("itisAppent", "YES");
                                } else {
                                    objectMap.put("itisAppent", "NO");
                                }
                                List<Comment> comments = commentMapper.selectBypublishId(publishs.getId());
                                objectMap.put("commentSize", comments.size());
                                objectMap.put("pFowordCount", publishs.getForwardCount());
                                List<Follow> followList = followMapper.selectByUserAndPublish(usersId, publishs.getId());
                                if (followList.size() > 0) {
                                    objectMap.put("itisFollow", "YES");
                                } else {
                                    objectMap.put("itisFollow", "NO");
                                }
                                objectMap.put("publishId", publishs.getId());
                                if (NotNullUtils.isNotNullObject(us.get("helpId"))) {
                                    objectMap.put("helpUsersId", us.get("helpId"));
                                } else {
                                    objectMap.put("helpUsersId", "");
                                }
                                objectList.add(objectMap);
                            }
                        }
                    }*/
                }
            }

            logger.info("获取获取好友的好友的发布和好友的好友帮转end**********************");

            logger.info("获取 好友的发布和好友的帮转begin**********************");
            //获取没有过滤我的好友
            UsersFillterUsers usersFillterUsers = usersFillterUsersMapper.selectByuserIds(usersId, c.getSpareTwo());
            if (!NotNullUtils.isNotNullObject(usersFillterUsers)) {
                //获取好友得发布列表
                List<Publish> publishList = publishMapper.selectByUsersIdsAndpublishType(c.getSpareTwo());
                for (Publish p : publishList) {
                    logger.info("好友的发布标记");
                    //判断朋友得发布有没有过滤我
                    UsersFillterPublishUsers fillterList = usersFillterPublishUsersMapper.selectByPublishIdAndFillterUsersId(p.getId(), usersId);
                    if (!NotNullUtils.isNotNullObject(fillterList)) {
                        Publish publish = publishMapper.selectByPrimaryKey(p.getId());
                        Users users = usersMapper.selectByPrimaryKey(publish.getUserId());
                        Map<String, Object> objectMap = new HashMap<>();
                        objectMap.put("userId", users.getId());
                        objectMap.put("userHead", users.getHeadImage());
                        objectMap.put("gender", users.getGender());
                        objectMap.put("userName", users.getName());
                        objectMap.put("pCity", publish.getCityName());
                        objectMap.put("pTime", RelativeDateFormat.format(publish.getCreatTime()));
                        objectMap.put("pTypeId", publish.getSpareOne());
                        objectMap.put("time", DateUtils.dateToStr(publish.getCreatTime(), "yyyy-MM-dd HH:mm:ss"));
                        objectMap.put("pTitle", publish.getTitle());
                        objectMap.put("pContent", publish.getContent());
                        objectMap.put("pRedPacakge", publish.getSpareTwo());
                        objectMap.put("pitisPaid", publish.getItIsPaid());
                        objectMap.put("connections", "我的好友");
                        objectMap.put("connectionUserId", "");
                        //是否受理
                        if (NotNullUtils.isNotNullObject(publishAcceptanceMapper.selectByAcceptanIdAndPublishId(usersId, publish.getId()))) {
                            objectMap.put("itisAppent", "YES");
                        } else {
                            objectMap.put("itisAppent", "NO");
                        }
                        List<Comment> comments = commentMapper.selectBypublishId(publish.getId());
                        objectMap.put("commentSize", comments.size());
                        objectMap.put("pFowordCount", publish.getForwardCount());
                        List<Follow> followList = followMapper.selectByUserAndPublish(usersId, publish.getId());
                        if (followList.size() > 0) {
                            objectMap.put("itisFollow", "YES");
                        } else {
                            objectMap.put("itisFollow", "NO");
                        }
                        objectMap.put("publishId", publish.getId());
                        objectMap.put("helpUsersId", "");
                        objectList.add(objectMap);
                    }
                }
                //获取好友得帮转列表
                List<Map<String, Object>> usersHelpList = usersHelpMapper.selectIndexByUsersId(c.getSpareTwo());
                for (Map<String, Object> u : usersHelpList) {
                    Map<String, Object> objectMap = new HashMap<>();
                    //发布详情
                    Publish publishs = publishMapper.selectByPrimaryKey(u.get("publishId").toString());
                    //发布人
                    Users users = usersMapper.selectByPrimaryKey(u.get("usersId").toString());
                    //帮转人
                    Users user = usersMapper.selectByPrimaryKey(u.get("helpId").toString());
                    //屏蔽转发的发布是用户的发布
                    if (!usersId.equals(users.getId())) {
                        objectMap.put("userId", users.getId());
                        objectMap.put("userHead", users.getHeadImage());
                        objectMap.put("gender", users.getGender());
                        objectMap.put("userName", users.getName());
                        objectMap.put("pCity", publishs.getCityName());
                        objectMap.put("pTime", RelativeDateFormat.format(publishs.getCreatTime()));
                        objectMap.put("pTypeId", publishs.getSpareOne());
                        objectMap.put("time", u.get("helpTime"));
                        objectMap.put("pTitle", publishs.getTitle());
                        objectMap.put("pContent", publishs.getContent());
                        objectMap.put("pRedPacakge", publishs.getSpareTwo());
                        objectMap.put("pitisPaid", publishs.getItIsPaid());
                        //是否受理
                        if (NotNullUtils.isNotNullObject(publishAcceptanceMapper.selectByAcceptanIdAndPublishId(usersId, publishs.getId()))) {
                            objectMap.put("itisAppent", "YES");
                        } else {
                            objectMap.put("itisAppent", "NO");
                        }
                        objectMap.put("connectionUserId", "");
                        objectMap.put("connections", user.getName());
                        List<Comment> comments = commentMapper.selectBypublishId(publishs.getId());
                        objectMap.put("commentSize", comments.size());
                        objectMap.put("pFowordCount", publishs.getForwardCount());
                        List<Follow> followList = followMapper.selectByUserAndPublish(usersId, publishs.getId());
                        if (followList.size() > 0) {
                            objectMap.put("itisFollow", "YES");
                        } else {
                            objectMap.put("itisFollow", "NO");
                        }
                        objectMap.put("publishId", publishs.getId());
                        if (NotNullUtils.isNotNullObject(u.get("helpUserId"))) {
                            objectMap.put("helpUsersId", u.get("helpUserId"));
                        } else {
                            objectMap.put("helpUsersId", "");
                        }

                        objectList.add(objectMap);
                    }
                }
            }


        }

        Collections.sort(objectList, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Date date1 = DateUtils.strToDate(o1.get("time").toString(), "yyyy-MM-dd HH:mm:ss");
                Date date2 = DateUtils.strToDate(o2.get("time").toString(), "yyyy-MM-dd HH:mm:ss");
                return date2.compareTo(date1);
            }
        });

        PageInfo pageInfo = new PageInfo(objectList);
        return pageInfo.getList();

    }

    /**
     * 判断是否是直接好友
     */
    private boolean getFriends(String usersId, String frieds) {
        List<Contacts> contacts = contactsMapper.seleByFriendsAndUsersId(usersId, frieds);
        boolean flag = false;
        if (contacts.size() > 0) {
            flag = true;
        }
        return flag;

    }


    /**
     * 搜索
     *
     * @param publishType
     * @param city
     * @param gender
     * @param itisPaid
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result serch(String usersId, String publishType, String city, String gender, String itisPaid, String pageNum, String pageSize) {

        List<Map<String, Object>> mapListG = new ArrayList<>();
        List<Map<String, Object>> mapsList = new ArrayList<>();
        if ("9".equals(publishType) || "10".equals(publishType) || "11".equals(publishType)) {
            mapListG = getIndexG(usersId, pageNum, pageSize, publishType);
        } else {
            mapsList = getIndexUsersInfo(usersId, pageNum, pageSize);
        }
        List<Map<String, Object>> maps = new ArrayList<>();
        if (NotNullUtils.isNotNullObject(publishType) || NotNullUtils.isNotNullObject(city) || NotNullUtils.isNotNullObject(gender) || NotNullUtils.isNotNullObject(itisPaid)) {
            String[] strings = publishType.split(",");
            String[] citys = city.split(",");
            //获取发布类型
            for (String s : strings) {
                for (String c : citys) {
                    for (Map<String, Object> map : mapsList) {
                        if (map.get("pTypeId").toString().equals(s) && map.get("pCity").equals(c) && map.get("pitisPaid").equals(itisPaid) && map.get("gender").equals(gender)) {
                            maps.add(map);
                        }
                    }
                    for (Map<String, Object> mapg : mapListG) {
                        maps.add(mapg);
                    }
                }
            }
        }
        return Result.success(maps);
    }


    /**
     * 保存用户选择城市记录
     *
     * @param usersId
     * @param cityName
     * @return
     */
    @Override
    public Result addCityHistory(String usersId, String cityName) {
        UsersCityHistory uc = new UsersCityHistory();
        uc.setId(UUIDUtils.getRandomUUID());
        uc.setCityName(cityName);
        uc.setUsersId(usersId);
        uc.setCreatTime(new Date());
        usersCityHistoryMapper.insertSelective(uc);
        return Result.success();
    }

    /**
     * 获取列表
     *
     * @param usersId
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result getUsersCityHistory(String usersId) {
        List<UsersCityHistory> ucs = usersCityHistoryMapper.selectByUsersId(usersId);
        return Result.success(ucs);
    }


    /**
     * 取消关注
     *
     * @param usersId
     * @param publishId
     * @return
     */
    @Override
    public Result removeFollow(String usersId, String publishId) {
        followMapper.deleteByUsersIdAndPublishId(usersId, publishId);
        return Result.success();
    }

    /**
     * 获取首页
     *
     * @param usersId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<Map<String, Object>> getIndexUsersInfos(String usersId, String pageNum, String pageSize) {
        PageHelper.startPage(new Integer(pageNum), new Integer(pageSize));
        //好友的发布列表
        List<Map<String, Object>> c = contactsMapper.selectByContUsers(usersId);
        for (Map<String, Object> map : c) {
            if (NotNullUtils.isNotNullObject(map.get("publishId"))) {
                logger.info("朋友的发布**********************************");
                //发布时间转换
                map.put("pTime", RelativeDateFormat.format(DateUtils.strToDate(map.get("pTime").toString(), "yyyy-MM-dd HH:mm:ss")));
                //是否受理
                if (NotNullUtils.isNotNullObject(publishAcceptanceMapper.selectByAcceptanIdAndPublishId(usersId, map.get("publishId").toString()))) {
                    map.put("itisAppent", "YES");
                } else {
                    map.put("itisAppent", "NO");
                }
                map.put("connections", "我的好友");
                map.put("connectionUserId", "");
                //评论次数
                map.put("commentSize", commentMapper.selectBypublishId(map.get("publishId").toString()).size());
                //是否关注
                if (followMapper.selectByUserAndPublish(usersId, map.get("publishId").toString()).size() > 0) {
                    map.put("itisFollow", "YES");
                } else {
                    map.put("itisFollow", "NO");
                }
                //帮转人id
                map.put("helpUsersId", "");
                logger.info("朋友的发布**********************************");
            }
            //朋友的朋友的发布
            List<Map<String, Object>> cs = contactsMapper.selectByContUsers(map.get("friends").toString());
            for (Map<String, Object> maps : cs) {
                if (NotNullUtils.isNotNullObject(maps.get("publishId"))) {
                    //过滤朋友的朋友有我
                    if (!maps.get("userId").equals(usersId)) {
                        map.put("userId", maps.get("userId"));
                        map.put("gender", maps.get("gender"));
                        map.put("userHead", maps.get("userHead"));
                        map.put("userName", maps.get("userName"));
                        map.put("pCity", maps.get("pCity"));
                        map.put("pTime", RelativeDateFormat.format(DateUtils.strToDate(maps.get("pTime").toString(), "yyyy-MM-dd HH:mm:ss")));
                        map.put("pTypeId", maps.get("pTypeId"));
                        map.put("pTitle", maps.get("pTitle"));
                        map.put("pContent", maps.get("pContent"));
                        map.put("pRedPacakge", maps.get("pRedPacakge"));
                        //是否受理
                        if (NotNullUtils.isNotNullObject(publishAcceptanceMapper.selectByAcceptanIdAndPublishId(usersId, maps.get("publishId").toString()))) {
                            map.put("itisAppent", "YES");
                        } else {
                            map.put("itisAppent", "NO");
                        }
                        //是否关注
                        if (followMapper.selectByUserAndPublish(usersId, maps.get("publishId").toString()).size() > 0) {
                            map.put("itisFollow", "YES");
                        } else {
                            map.put("itisFollow", "NO");
                        }
                        //评论次数
                        map.put("commentSize", commentMapper.selectBypublishId(maps.get("publishId").toString()).size());
                        map.put("connections", map.get("userName"));
                        map.put("connectionUserId", map.get("userId"));
                    }
                }
            }
        }
        PageInfo pageInfo = new PageInfo(c);
        return pageInfo.getList();
    }

    /**
     * 公益发布列表
     *
     * @param usersId  用户id
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<Map<String, Object>> getIndexG(String usersId, String pageNum, String pageSize, String type) {
        PageHelper.startPage(new Integer(pageNum), new Integer(pageSize));
        List<Map<String, Object>> publishList = publishMapper.selectPublishList(type);
        for (Map<String, Object> maps : publishList
        ) {
            //判断是否关注
            List<Follow> followList = followMapper.selectByUserAndPublish(usersId, maps.get("pid").toString());
            if (followList.size() > 0) {
                maps.put("itisFollow", "YES");
            } else {
                maps.put("itisFollow", "NO");
            }
            //照片信息
            maps.put("pimage", NotNullUtils.sliptList(maps.get("pimage").toString()));
            //发布时间
            maps.put("ptime", RelativeDateFormat.format(DateUtils.strToDate(maps.get("ptime").toString(), "yyyy-MM-dd HH:mm:ss")));
        }
        return publishList;
    }

    /**
     * @return
     */
    @Override
    public Result getOpens() {
        Map<String, Object> map = new HashMap<>();
        map.put("open", "NO");
        return Result.success(map);
    }


}
